package com.traffic.between.service;

import java.net.URI;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;

import net.sf.json.JSONObject;

@SuppressWarnings("deprecation")
public class YunLiuLiangServiceImpl {
	private static Logger logger = Logger.getLogger(YunLiuLiangServiceImpl.class);
	public static YunLiuLiangServiceImpl service = new YunLiuLiangServiceImpl();
	public static String str11 = "querychenxiangtest123456975d2a730348fcbed0e1cbaddade2267";

	private static String HOST_ORDER_PATH = BetweenProperties.YUNLL_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.YUNLL_ORDERSTATUS_URL;
	private static String YUNLL_APPKEY = BetweenProperties.YUNLL_APPKEY;
	private static String YUNLL_SECURITYKEY = BetweenProperties.YUNLL_SECURITYKEY;

	@SuppressWarnings({ "resource" })
	public String order(String productId, String phoneNo, String cstmOrderNo, String callbackURL) {
		
		String result = "";

		String service = "order";
		String busi_type = "4";

		/**
		 * 排序后的待加密的签名 sign=md5(service merchant_id merchant_orderid
		 * charge_number charge_money busi_type back_urlkey)
		 * 
		 * service = "order"; merchant_id//商家账号 merchant_orderid//商家订单
		 * charge_number充值号码 charge_money充值金额提单只要数字(计量单位:话费单位为元，Q币单位为个，流量单位为M)
		 * busi_type业务类型：0-手机充值，1-Q币充值，2-电信固网，3-联通固网，4-漫游流量，5-非漫游流量 back_url
		 * 通知接口的URL地址，如果需要回调，必填 usr_province如果为Q币充值，该项必填
		 * package_type如果不传该值，默认为月包
		 * 
		 */
		String waitSig = service + YUNLL_APPKEY + cstmOrderNo + phoneNo + productId + busi_type + callbackURL
				+ YUNLL_SECURITYKEY;
		// 签名
		String sign = getMD5(waitSig.trim());
		// 参数
		String params = "service=" + service + "&merchant_id=" + YUNLL_APPKEY + "&merchant_orderid=" + cstmOrderNo
				+ "&charge_number=" + phoneNo + "&charge_money=" + productId + "&busi_type=" + busi_type + "&back_url="
				+ callbackURL + "&sign=" + sign;
		logger.info("between- 云流量订单YunLiuLiangServiceImpl.order() 订购请求params<>:"+params);

		HttpClient httpClient = new DefaultHttpClient();
		// 连接时间，指的是连接一个url的连接等待时间。 超时报异常
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		// 数据传输时间，指的是连接上一个url，获取response的返回等待时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
		// Get请求
		HttpGet httpget = new HttpGet(HOST_ORDER_PATH);
		try {
			httpget.setURI(new URI(httpget.getURI().toString() + "?" + params));

			// 发送请求
			HttpResponse httpResponse = httpClient.execute(httpget);
			int statusCode = httpResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				logger.error("Method failed:" + httpResponse.getStatusLine());
				return "{\"resultCode\": \"01\",\"resultMsg\":\"订单异常\"}";
			}

			// 获取返回数据
			HttpEntity entity = httpResponse.getEntity();
			String body = EntityUtils.toString(entity, Charset.forName("UTF-8"));

			// 将body格式转为json(result_code= &result_desc=&orderid=)
			body = "{\"" + body.replace("=", "\":\"").replace("&", "\",\"") + "\"}";
			logger.info("between- 云流量订单YunLiuLiangServiceImpl.order() 订购请求response:" + body);

			JSONObject resultJson = JSONObject.fromObject(body);

			// 返回0000为充值请求提交成功，其他错误码为失败
			String coopOrderStatus = (String) resultJson.get("result_code");
			if ("0000".equals(coopOrderStatus)) {
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("resultCode", "00");
				map.put("resultMsg", "订单成功");
				map.put("orderId",resultJson.getString("orderid"));
				result = new Gson().toJson(map);
			} else {
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("resultCode", "01");
				map.put("resultMsg", resultJson.getString("result_desc"));
				result = new Gson().toJson(map);
			}
			if (entity != null) {
				EntityUtils.consume(entity);
			}

		} catch (Exception e) {
			logger.info("云流量订购请求异常"+e.getMessage());
		} finally {
			httpget.releaseConnection();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	@SuppressWarnings({ "resource" })
	public String orderStatus(String cstmOrderNo) {

		logger.info("between- 云流量状态YunLiuLiangServiceImpl.orderStatus() 查询请求cstmOrderNo = " + cstmOrderNo);

		String result = "";
		String service = "query";
		/**
		 * 排序后的待加密的签名
		 * 
		 * service=query&=merchant_id=&merchant_orderid=&sign=xxxx
		 * sign=md5(service merchant_id merchant_orderid key)
		 * 
		 */
		String signstr = (service + YUNLL_APPKEY + cstmOrderNo + YUNLL_SECURITYKEY).trim();
		System.out.println(str11.equals(signstr));
		// md5加密后sign
		String sign = YunLiuLiangServiceImpl.getMD5(String.valueOf(signstr));
		String param = "service=" + service + "&merchant_id=" + YUNLL_APPKEY + "&merchant_orderid=" + cstmOrderNo
				+ "&sign=" + sign;

		HttpClient httpClient = new DefaultHttpClient();
		// 连接时间，指的是连接一个url的连接等待时间。 超时报异常
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		// 数据传输时间，指的是连接上一个url，获取response的返回等待时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
		// Get请求
		HttpGet httpget = new HttpGet(HOST_ORDERSTATUS_PATH);
		try {
			httpget.setURI(new URI(httpget.getURI().toString() + "?" + param));

			// 发送请求
			HttpResponse httpResponse = httpClient.execute(httpget);
			int statusCode = httpResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				logger.error("Method failed:" + httpResponse.getStatusLine());
				return "{\"resultCode\": \"01\",\"resultMsg\":\"订单异常\"}";
			}

			// 获取返回数据
			HttpEntity entity = httpResponse.getEntity();
			String body = EntityUtils.toString(entity, Charset.forName("UTF-8"));

			body = "{\"" + body.replace("=", "\":\"").replace("&", "\",\"") + "\"}";
			logger.info("between- 云流量状态YunLiuLiangServiceImpl.orderStatus() 查询响应response:" + body);
			// 将body格式转为json(result_code= &result_desc=&charge_status=)
			JSONObject resultJson = JSONObject.fromObject(body);

			String coopOrderStatus = (String) resultJson.get("result_code");
			if ("0000".equals(coopOrderStatus)) {
				// chargestatus 充值状态:SUCC成功，FAIL失败，DEAL正在处理
				String chargestatus = (String) resultJson.get("chargestatus");
				if ("SUCC".equals(chargestatus)) {
					result = "{\"resultCode\": \"00\",\"resultMsg\":\"订购成功\"}";
				} else if ("DEAL".equals(chargestatus)) {
					result = "{\"resultCode\": \"01\",\"resultMsg\":\"订购中\"}";
				} else if ("FAIL".equals(chargestatus)) {
					result = "{\"resultCode\": \"02\",\"resultMsg\":\"订购失败\"}";
				}else {
					result = "{\"resultCode\": \"01\",\"resultMsg\":\"订购中\"}";
				}

			} else {
				result = "{\"resultCode\": \"01\",\"resultMsg\":\"订购中\"}";
			}
			if (entity != null) {
				EntityUtils.consume(entity);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("between- 云流量订购请求上游异常:" + e.getMessage());
		} finally {
			httpget.releaseConnection();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}
	
	public static void main(String[] args) {
		String body = "{\"result_code\":\"1106\",\"result_desc\":\"该面值暂时不能充值\",\"orderid\":\"\"}";
		JSONObject resultJson = JSONObject.fromObject(body);
		String result = "";
		// 返回0000为充值请求提交成功，其他错误码为失败
		String coopOrderStatus = (String) resultJson.get("result_code");
		if ("0000".equals(coopOrderStatus)) {
			result = "{\"resultCode\": \"00\",\"resultMsg\":\"订单成功\",\"orderId\":"
					+ String.valueOf(resultJson.get("orderid")).toString() + "}";
		} else {
			result = "{\"resultCode\": \"01\",\"resultMsg\":" + (String) resultJson.get("result_desc") + "}";
		}
		JSONObject resultJson1 = JSONObject.fromObject(result);
		System.out.println(resultJson1.get("resultMsg"));
	}
}
